package com.xhc.lock;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

@Component
public class DisLockClient {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String uuidPrefix;

    private ZooKeeper zooKeeper;

    public DisLockClient() {
        this.uuidPrefix = UUID.randomUUID().toString();
    }

    @PostConstruct
    public void InitZoo(){
        CountDownLatch latch = new CountDownLatch(1);
        try {
            zooKeeper = new ZooKeeper("localhost:2181", 30000, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    Event.KeeperState state = watchedEvent.getState();
                    Event.EventType type = watchedEvent.getType();
                    if (Event.KeeperState.SyncConnected.equals(state) && Event.EventType.None.equals(type)){
                        System.out.println("连接成功");
                        latch.countDown();
                    }else if (Event.KeeperState.Closed.equals(state)){
                        System.out.println("连接关闭了");
                    }
                }
            });
            latch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void destroyZoo(){
        try {
            if (zooKeeper != null){
                zooKeeper.close();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 构建redis锁
     * @param lockName
     * @return
     */
    public MyRedisLock buildRedisLock(String lockName){
        return new MyRedisLock(redisTemplate, lockName, this.uuidPrefix);
    }


    /**
     * 构建zookeeper锁
     * @param lockName
     * @return
     */
    public MyZookeeperLock buildZookeeperLock(String lockName){
        return new MyZookeeperLock(zooKeeper, lockName);
    }
}
